package com.wuseguang.springcloud.service.impl;


import com.wuseguang.springcloud.Classcardservice.ClassCardFieldService;
import com.wuseguang.springcloud.dao.jdbc.BanCardsJdbc;
import com.wuseguang.springcloud.service.BanCardsService;
import com.wuseguang.springcloud.util.CodeUtil;
import com.wuseguang.springcloud.util.DateUtil;
import com.wuseguang.springcloud.util.HttpRequestUtil;
import com.wuseguang.springcloud.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class BanCardsServiceImpl implements BanCardsService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BanCardsJdbc banCardJdbc;

    @Autowired
    private ClassCardFieldService classCardFieldService;

    private Integer flag = 0;

    //关机时间
    private static String gtime = "";
    //节假日配置时间
    private static String htime = "00:01:00";


    /**
     * @描述 先判断是否有常规和节假日时间，最后在处理两个条件同时存在的情况
     * @创建人 zm
     * @创建时间 2020/1/3
     */
    @Override
    public Map<String, String> SwitchingTime(String deviceid) {
        Map<String, String> map = new HashMap<String, String>();
        Map<String, Object> stringObjectMap4 = banCardJdbc.queryDevice(deviceid);
        if (stringObjectMap4 == null) {
            return map;
        }
        String school_id = String.valueOf(stringObjectMap4.get("school_id"));
        Object id = stringObjectMap4.get("id");

        //更新开关机时间心跳
        classCardFieldService.pushClassCard(Integer.parseInt(id.toString()), "holidayheartbeat", flag);

        gtime = DateUtil.addMinutes(3);
        //查 所有常规时间
        String sql3 = "SELECT monday,tuesday,wednesday,thursday,friday,saturday,sunday FROM bancard  WHERE school_id=? AND id=?";
        Map<String, Object> stringObjectMap2 = banCardJdbc.queryMap1(sql3, school_id, id);
        logger.info(" SwitchingTime==>常规开关机时间，stringObjectMap2.toString()={}", stringObjectMap2.toString());
        String sql4 = "SELECT holiday_st,holiday_et FROM holiday h,holiday_deviceid d,bancard  c WHERE h.id=d.holiday_id AND c.id=d.device_id AND c.school_id=? AND d.device_id=? AND d.state=1 AND TO_DAYS(holiday_et)>=TO_DAYS(?) ORDER BY holiday_st";
        List<Map<String, Object>> stringObjectMap3 = null;
        try {
            logger.info("SwitchingTime==>school_id ={},id={},DateUtil.time()={}", school_id, id, DateUtil.time());
            stringObjectMap3 = banCardJdbc.queryListMap(sql4, school_id, id, DateUtil.time());
        } catch (Exception e) {
            logger.info("Exception e={}", e);
        }
        //判断是否有  有效的节假日  过期的节假日视为无效  还没到时间的节假日视为有效
        if (stringObjectMap3 != null && stringObjectMap3.size() > 0) {
            logger.info("SwitchingTime==>stringObjectMap3 != null && stringObjectMap3.size() > 0");
            String sql = " SELECT holiday_st,holiday_et FROM holiday h,holiday_deviceid d ,bancard  c WHERE h.id=d.holiday_id AND c.id=d.device_id  AND c.school_id=? AND d.device_id=? AND d.state=1 AND  TO_DAYS(holiday_st)<=TO_DAYS(?) AND TO_DAYS(holiday_et)>=TO_DAYS(?) ORDER BY holiday_st LIMIT 0,1";
            Map<String, Object> stringObjectMap = null;
            try {
                stringObjectMap = banCardJdbc.queryMap(sql, school_id, id, DateUtil.time(), DateUtil.time());
            } catch (Exception e) {
                logger.info("Exception e={}", e);
            }
            //当前时间在节假日期间 关时间时间 取 当前服务器时间+3分钟
            if (stringObjectMap != null && stringObjectMap.size() > 0) {
                map.put("shutdowntime", gtime);
                String sql2 = " SELECT holiday_st,holiday_et FROM holiday h,holiday_deviceid d,bancard  c WHERE h.id=d.holiday_id AND c.id=d.device_id  AND c.school_id=? AND d.device_id=? AND d.state=1 AND TO_DAYS(holiday_st)>=TO_DAYS(?) ORDER BY holiday_st ";
                List<Map<String, Object>> holiday_et = banCardJdbc.queryListMap(sql2, school_id, id, stringObjectMap.get("holiday_et"));
                //判断假期时间是否有衔接
                if (holiday_et != null && holiday_et.size() > 0) {
                    String s = (String) stringObjectMap.get("holiday_et");
                    for (int i = 0; i < holiday_et.size(); i++) {
                        logger.info("SwitchingTime,holiday_et={}", s);
                        Map<String, Object> stringObjectMap1 = holiday_et.get(i);
                        String holiday_st = (String) stringObjectMap1.get("holiday_st");
                        //时间 衔接断裂   例如： 2020-01-01~ 2020-01-02  2020-01-03~ 2020-01-04  2020-01-06~ 2020-01-07   获取时间 为 2020-01-04
                        if (DateUtil.getDay(s, holiday_st) != 1) {
                            if (stringObjectMap2 == null || stringObjectMap2.size() == 0) {
                                String addTime = DateUtil.getAddTime(DateUtil.addDays(s, 1), htime);
                                map.put("boottime", addTime);
                                return map;
                            }
                            long holiday_st1 = DateUtil.getDay(s, holiday_st);
                            //时间 间隔超过 7天 的按 7天循环
                            if (holiday_st1 >= 7) {
                                for (int j = 1; j < 8; j++) {
                                    String s1 = DateUtil.addDays(s, j);
                                    String weekEnglish = DateUtil.getWeekEnglish(s1);
                                    if (!"".equals(weekEnglish)) {
                                        String o = (String) stringObjectMap2.get(weekEnglish);
                                        if (o != null && !"".equals(o)) {
                                            o = gettime(o);
                                            String addTime = DateUtil.getAddTime(s1, o);
                                            logger.info("stringObjectMap==>j < 8,boottime={}", addTime);
                                            map.put("boottime", addTime);
                                            return map;
                                        }
                                    }
                                }
                                s = (String) stringObjectMap1.get("holiday_et");
                            } else {
                                //时间 间隔小于7天的
                                for (int j = 1; j < holiday_st1; j++) {
                                    String s1 = DateUtil.addDays(s, j);
                                    String weekEnglish = DateUtil.getWeekEnglish(s1);
                                    if (!"".equals(weekEnglish)) {
                                        String o = (String) stringObjectMap2.get(weekEnglish);
                                        if (o != null && !"".equals(o)) {
                                            o = gettime(o);
                                            String addTime = DateUtil.getAddTime(s1, o);
                                            logger.info("stringObjectMap==>j < holiday_st1,boottime={}", addTime);
                                            map.put("boottime", addTime);
                                            return map;
                                        }
                                    }
                                }
                                s = (String) stringObjectMap1.get("holiday_et");
                            }
                        } else {
                            s = (String) stringObjectMap1.get("holiday_et");
                            String addTime = DateUtil.getAddTime(DateUtil.addDays(s, 1), htime);
                            map.put("boottime", addTime);
                        }
                        //最后一个 节假日特殊处理
                        if (i == holiday_et.size() - 1) {
                            for (int j = 1; j < 8; j++) {
                                String s1 = DateUtil.addDays(s, j);
                                String weekEnglish = DateUtil.getWeekEnglish(s1);
                                if (!"".equals(weekEnglish)) {
                                    String o = (String) stringObjectMap2.get(weekEnglish);
                                    if (o != null && !"".equals(o)) {
                                        o = gettime(o);
                                        map.put("boottime", DateUtil.getAddTime(s1, o));
                                        return map;
                                    }
                                }
                            }
                        }
                    }
                } else {//该节假日 为最后一个节假日
                    String s = (String) stringObjectMap.get("holiday_et");
                    if (stringObjectMap2 == null || stringObjectMap2.size() == 0) {
                        String addTime = DateUtil.getAddTime(DateUtil.addDays(s, 1), htime);
                        map.put("boottime", addTime);
                        return map;
                    }
                    for (int j = 1; j < 8; j++) {
                        String s1 = DateUtil.addDays(s, j);
                        String weekEnglish = DateUtil.getWeekEnglish(s1);
                        if (!"".equals(weekEnglish)) {
                            String o = (String) stringObjectMap2.get(weekEnglish);
                            if (o != null && !"".equals(o)) {
                                o = gettime(o);
                                String addTime = DateUtil.getAddTime(s1, o);
                                map.put("boottime", addTime);
                                return map;
                            }
                        }
                    }
                }
            } else {
                //不在节假日时间段内，节假日还没开始  预处理
                String sql5 = " SELECT holiday_st,holiday_et FROM holiday h,holiday_deviceid d,bancard  c WHERE h.id=d.holiday_id AND c.id=d.device_id  AND c.school_id=? AND d.device_id=? AND d.state=1 AND TO_DAYS(holiday_st)>TO_DAYS(?) ORDER BY holiday_st";
                List<Map<String, Object>> stringObjectMap1 = null;
                try {
                    stringObjectMap1 = banCardJdbc.queryListMap(sql5, school_id, id, DateUtil.time());
                } catch (Exception e) {
                    logger.info("Exception e={}", e);
                }
                //如果为空就是 后续没有节假日
                if (stringObjectMap1 == null) {
                    return getDailySwitch(stringObjectMap2);
                } else {
                    String holiday_st = (String) stringObjectMap1.get(0).get("holiday_st");
                    if (stringObjectMap2 == null || stringObjectMap2.size() == 0) {//都为 null 表示 没有常规开关机时间
                        map.put("shutdowntime", DateUtil.getAddTime(holiday_st, htime));
                        String s = "";
                        for (int i = 0; i < stringObjectMap1.size(); i++) {
                            //时间 衔接断裂   例如： 2020-01-01~ 2020-01-02  2020-01-03~ 2020-01-04  2020-01-06~ 2020-01-07   获取时间 为 2020-01-04
                            if (i != 0 && (DateUtil.getDay(s, (String) stringObjectMap1.get(i).get("holiday_st")) != 1)) {
                                break;
                            }
                            s = (String) stringObjectMap1.get(i).get("holiday_et");
                        }
                        String addTime = DateUtil.getAddTime(DateUtil.addDays(s, 1), htime);
                        map.put("boottime", addTime);
                        return map;
                    } else {//有常规时间
                        return getDailySwitchAndHoliday(stringObjectMap2, stringObjectMap1);
                    }
                }
            }
        } else {// 没有有效的节假日
            return getDailySwitch(stringObjectMap2);
        }
        return map;
    }


    public String gettime(String time) {
        logger.info("s gettime(String time)={}", time);
        int a = 0;
        String[] split = time.split(",");
        for (int k = 0; k < split.length; k++) {
            String[] split2 = split[k].split("-");
            for (int i = 0; i < split2.length; i++) {
                if (split2[i] != null && !"".equals(split2[i]) && !"null".equals(split2[i])) {
                    time = split2[i];
                    a = 1;
                    break;
                }
            }
            if (a == 1) {
                break;
            }
        }
        logger.info("e gettime(String time)={}", time);
        return time;
    }


    public Map<String, String> getDailySwitchAndHoliday(Map<String, Object> stringObjectMap2, List<Map<String, Object>> stringObjectMap1) {
        String time = DateUtil.time();
        Map<String, String> map = new HashMap<String, String>();
        List<String> listSorttime = getListSorttime(stringObjectMap2);//获取 一个时间队列 集合，里面最少会有一个时间段,两个时间
        logger.info("getDailySwitchAndHoliday=>listSorttime.toString()={}", listSorttime.toString());
        String holiday_st = (String) stringObjectMap1.get(0).get("holiday_st");
        for (int i = 0; i < listSorttime.size(); i++) {
            String s = listSorttime.get(i);
            if (i % 2 == 0) {
                if (DateUtil.compTime(time, listSorttime.get(i + 1)) > 0) {
                    continue;
                }
                long l = DateUtil.compTime(time, s);
                long l2 = DateUtil.compTime(time, listSorttime.get(i + 1));
                if (DateUtil.getDay(s, holiday_st) > 0) {//今天不是
                    if (l + 5 <= 0) {// 在开机时间5分钟 之前
                        logger.info("l+5 <= 0");
                        map.put("shutdowntime", gtime);
                        map.put("boottime", s);
                        return map;
                    } else if (l2 >= 0) { //在 关机时间之后
                        String s2 = listSorttime.get(i + 2);
                        logger.info("l2 >=0");
                        long l3 = DateUtil.compTime(time, s2);
                        long l4 = DateUtil.getDay(s2, holiday_st);
                        if (l4 > 0) {
                            logger.info("l4 > 0");
                            if (l3 + 5 < 0) {
                                map.put("shutdowntime", gtime);
                                map.put("boottime", s2);
                            } else {
                                String s1 = listSorttime.get(i + 3);
                                map.put("shutdowntime", s1);
                                if (DateUtil.compTime(time, s1) > 0) {
                                    map.put("shutdowntime", gtime);
                                }
                                map.putAll(getDailySwitchTime(holiday_st, stringObjectMap1, stringObjectMap2, listSorttime.get(i + 4)));
                            }
                            return map;
                        } else {
                            map.put("shutdowntime", gtime);
                            map.putAll(getDailySwitchTime(holiday_st, stringObjectMap1, stringObjectMap2, s2));
                            return map;
                        }
                    } else {//在开机时间
                        String s2 = listSorttime.get(i + 2);
                        map.put("shutdowntime", listSorttime.get(i + 1));
                        map.putAll(getDailySwitchTime(holiday_st, stringObjectMap1, stringObjectMap2, s2));
                    }
                    return map;
                } else {
                    map.put("shutdowntime", gtime);
                    map.putAll(getDailySwitchTime(holiday_st, stringObjectMap1, stringObjectMap2, s));
                    return map;
                }
            }
        }
        return null;
    }


    /**
     * @描述 判断 日常时间和节假日的关系
     * @创建人 zm
     * @创建时间 2020/1/7
     */
    public Map<String, String> getDailySwitchTime(String holiday_st, List<Map<String, Object>> stringObjectMap1, Map<String, Object> stringObjectMap2, String s2) {
        Map<String, String> map = new HashMap<String, String>();
        //查看 第二段时间是否在节假日前
        if (DateUtil.getDay(s2, holiday_st) > 0) {
            map.put("boottime", s2);
            return map;
        } else {
            String s = DateUtil.time();
            //查看节假日是否有衔接
            logger.info("getDailySwitchTime==>stringObjectMap1={}", stringObjectMap1.toString());
            for (int i = 0; i < stringObjectMap1.size(); i++) {
                long holiday_st1 = DateUtil.getDay(s, (String) stringObjectMap1.get(i).get("holiday_st"));
                if (i != 0 && holiday_st1 != 1) {
                    if (holiday_st1 >= 7) {
                        for (int j = 1; j < 8; j++) {
                            String s1 = DateUtil.addDays(s, j);
                            String weekEnglish = DateUtil.getWeekEnglish(s1);
                            if (!"".equals(weekEnglish)) {
                                String o = (String) stringObjectMap2.get(weekEnglish);
                                if (o != null && !"".equals(o)) {
                                    o = gettime(o);
                                    String addTime = DateUtil.getAddTime(s1, o);
                                    map.put("boottime", addTime);
                                    return map;
                                }
                            }
                        }
                        s = (String) stringObjectMap1.get(i).get("holiday_et");
                    } else {
                        //时间 间隔小于7天的
                        for (int j = 1; j < holiday_st1; j++) {
                            String s1 = DateUtil.addDays(s, j);
                            String weekEnglish = DateUtil.getWeekEnglish(s1);
                            if (!"".equals(weekEnglish)) {
                                String o = (String) stringObjectMap2.get(weekEnglish);
                                if (o != null && !"".equals(o)) {
                                    o = gettime(o);
                                    String addTime = DateUtil.getAddTime(s1, o);
                                    map.put("boottime", addTime);
                                    return map;
                                }
                            }
                        }
                        s = (String) stringObjectMap1.get(i).get("holiday_et");
                    }
                } else {
                    s = (String) stringObjectMap1.get(i).get("holiday_et");
                }
                if (i == stringObjectMap1.size() - 1) {
                    for (int j = 1; j < 8; j++) {
                        String s1 = DateUtil.addDays(s, j);
                        String weekEnglish = DateUtil.getWeekEnglish(s1);
                        if (!"".equals(weekEnglish)) {
                            String o = (String) stringObjectMap2.get(weekEnglish);
                            if (o != null && !"".equals(o)) {
                                o = gettime(o);
                                String addTime = DateUtil.getAddTime(s1, o);
                                logger.info("getDailySwitchTime==>boottime={}", addTime);
                                map.put("boottime", addTime);
                                return map;
                            }
                        }
                    }
                }
            }
        }
        return map;
    }

    public Map<String, String> getDailySwitch(Map<String, Object> stringObjectMap2) {
        Map<String, String> map = new HashMap<String, String>();
        String time = DateUtil.time();
        //先判断是否有日常开关机时间
        if (stringObjectMap2 == null || stringObjectMap2.size() == 0) {//都为 null 表示 没有开关机时间 和节假日时间  永不关机
            logger.info("getDailySwitch==>{stringObjectMap2 == null || stringObjectMap2.size() == 0}");
            return map;
        } else {
            List<String> listSorttime = getListSorttime(stringObjectMap2);//获取 一个时间队列 集合，里面最少会有一个时间段,两个时间
            logger.info("getDailySwitch==>listSorttime={}", listSorttime.toString());
            for (int i = 0; i < listSorttime.size(); i++) {
                String s = listSorttime.get(i);
                String s1 = listSorttime.get(i + 1);
                if (i % 2 == 0) {
                    if (DateUtil.compTime(time, s1) > 0) {
                        continue;
                    }
                    long l = DateUtil.compTime(time, s);
                    long l2 = DateUtil.compTime(time, s1);
                    logger.info("getDailySwitch==>listSorttime.size()={}", listSorttime.size());
                    if (l + 5 <= 0) {// 在开机时间5分钟 之前
                        logger.info("getDailySwitch==>l + 5<0");
                        map.put("shutdowntime", gtime);
                        map.put("boottime", s);
                        return map;
                    } else if (l2 >= 0) { //在 关机时间之后
                        String s2 = listSorttime.get(2);
                        logger.info("getDailySwitch==>l2>=0");
                        long l3 = DateUtil.compTime(DateUtil.time(), s2);
                        if (l3 + 5 < 0) {
                            logger.info("getDailySwitch==>l3 + 5 < 0");
                            map.put("shutdowntime", gtime);
                            map.put("boottime", s2);
                        } else {
                            map.put("shutdowntime", listSorttime.get(i + 3));
                            map.put("boottime", listSorttime.get(i + 4));
                        }
                        return map;
                    } else { //在开机时间内 开机
                        map.put("shutdowntime", s1);
                        map.put("boottime", listSorttime.get(i + 2));
                        return map;
                    }
                }
            }
            return null;
        }
    }

    /**
     * @描述 时间进行排序
     * @创建人 zm
     * @创建时间 2020/1/14
     */
    public List<String> getListSorttime(Map<String, Object> stringObjectMap2) {
        List<String> arrayList = new ArrayList<String>();
        //循环两次 保证有两组数据  然后和 节假日对比
        for (int j = 0; j < 21; j++) {
            String s1 = DateUtil.addDays(DateUtil.time(), j);
            String weekEnglish = DateUtil.getWeekEnglish(s1);
            if (!"".equals(weekEnglish)) {
                String o = (String) stringObjectMap2.get(weekEnglish);
                if (o != null && !"".equals(o)) {
                    String[] split = o.split(",");
                    for (int k = 0; k < split.length; k++) {
                        String[] split2 = split[k].split("-");
                        for (int i = 0; i < split2.length; i++) {
                            if (split2[i] != null && !"".equals(split2[i]) && !"null".equals(split2[i])) {
                                String addTime = DateUtil.getAddTime(s1, split2[i]);
                                arrayList.add(addTime);
                            }
                        }
                    }
                }
            }
        }
        Collections.sort(arrayList, new Comparator<String>() {
            DateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            @Override
            public int compare(String o1, String o2) {
                try {
                    return f.parse(o1).compareTo(f.parse(o2));
                } catch (ParseException e) {
                    throw new IllegalArgumentException(e);
                }
            }
        });
        logger.info("getListSorttime==>,sarrayList={}", arrayList.toString());
        return arrayList;
    }


    /**
     * @描述 获取天气预报
     * @创建人 zm
     * @创建时间 2020/2/15
     */
    @Override
    public String queryWeather(String deviceid) {
        String sql = "SELECT t.cname string FROM bancard b,school s,district d,city t WHERE b.deviceid=? AND b.school_id=s.id AND d.id=s.district_id AND d.cid=t.id ";
        String s = banCardJdbc.queryString(sql, deviceid);
        if (!StringUtils.isEmpty(s)) {
            String sql1 = "SELECT c.citycode string FROM citylist c WHERE c.citytext=?";
            s = s.indexOf("市") == s.length() - 1 ? s.substring(0, s.length() - 1) : s;
            String s1 = banCardJdbc.queryString(sql1, s);
            if (!StringUtils.isEmpty(s1)) {
                String weatherInfo = HttpRequestUtil.getWeatherInfo("http://wthrcdn.etouch.cn/weather_mini?citykey=", s1);
                return weatherInfo;
            }
        }
        return null;
    }

    /**
     * @描述 更新时间心跳 ，用于判断 在线/离线
     * @创建人 zm
     * @创建时间 2020/2/15
     */
    @Override
    public Map<String, Integer> updateHeartBeatTime(String deviceid) {
        Map<String, Integer> map = new HashMap<>();
        Map<String, Object> stringObjectMap = banCardJdbc.queryDevice(deviceid);
        String sql = "UPDATE bancard SET heartbeattime=NOW() WHERE deviceid=?";
        banCardJdbc.updateByParameter(sql, deviceid);
        if (stringObjectMap == null) {
            logger.info("updateHeartBeatTime,state=1,deviceid={}", deviceid);
            map.put("state", 1);
            return map;
        }

        Object clientid = stringObjectMap.get("clientid");
        Object pstatus = stringObjectMap.get("pstatus");
        if (clientid == null || StringUtils.isEmpty(clientid.toString())) {
            logger.info("updateHeartBeatTime,state=2,deviceid={}", deviceid);
            map.put("state", 2);
            return map;
        }
        if (pstatus != null && "1".equals(pstatus.toString())) {
            map.put("state", 4);
            logger.info("updateHeartBeatTime,state=4,deviceid={}", deviceid);
            return map;
        }
        logger.info("updateHeartBeatTime,state=3,deviceid={}", deviceid);
        map.put("state", 3);
        return map;
    }


    /**
     * @描述 查询班级信息和班主任信息
     * @创建人 zm
     * @创建时间 2020/2/15
     */
    @Override
    public Map<String, Object> queryClassInformation(String deviceid) {
        Map<String, Object> stringObjectMap = banCardJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return null;
        }
        Object classid = stringObjectMap.get("classid");
        Object class_teacher_id = stringObjectMap.get("class_teacher_id");
        Object teachername = stringObjectMap.get("teachername");
        Object head_portrait = stringObjectMap.get("head_portrait");
        Object id = stringObjectMap.get("id");
        Map<String, Object> teacherMap = new HashMap<>();
        if (class_teacher_id != null) {
            String sql = "SELECT e.id courseid ,GROUP_CONCAT(DISTINCT e.name)  subject " +
                    "   FROM classes a ,course e,teacher t,teacher_role r,roles s WHERE a.id=?   AND " +
                    "   t.id=r.teacher_id AND e.id=s.course_id AND s.id=r.role_id  AND a.id=r.pid " +
                    "    AND t.id=? AND s.type=1 AND r.type=3 GROUP BY a.id";
            try {
                teacherMap = banCardJdbc.queryMap(sql, classid, class_teacher_id);
            } catch (Exception e) {
                logger.info("queryClassInformation-->error={}", e);
            }
        }
        teacherMap.put("class_teacher_id", class_teacher_id);
        teacherMap.put("teachername", teachername);
        teacherMap.put("head_portrait", head_portrait);
        //更新班级信息心跳
        // classCardFieldService.pushClassCard(Integer.parseInt(id.toString()), "classflag", flag);
        String sql = " UPDATE bancard SET classflag=0 WHERE deviceid=?";
        banCardJdbc.updateByParameter(sql, deviceid);
        return teacherMap;
    }


    @Override
    public Map<String, Object> querySchoolInformation(String deviceid) {
        Map<String, Object> stringObjectMap = banCardJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return null;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("classid", stringObjectMap.get("classid"));
        map.put("classname", stringObjectMap.get("classname"));
        map.put("class_icon", stringObjectMap.get("class_icon"));
        map.put("school_id", stringObjectMap.get("school_id"));
        map.put("school_name", stringObjectMap.get("school_name"));
        //更新班级信息心跳
        //classCardFieldService.deviceidAndCards(deviceid, "classflag", "0");
        String sql = " UPDATE bancard SET classflag=0 WHERE deviceid=?";
        banCardJdbc.updateByParameter(sql, deviceid);
        return map;
    }


    /**
     * @描述 查询班级图片
     * @创建人 zm
     * @创建时间 2020/2/15
     */
    @Override
    public List<Map<String, Object>> queryClassPictures(String deviceid) {
        Map<String, Object> stringObjectMap = banCardJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return null;
        }
        Object classid = stringObjectMap.get("classid");
        Object id = stringObjectMap.get("id");
        String sql = "  SELECT   s.id, s.name, SUBSTRING_INDEX(SUBSTRING_INDEX(  s.pictyres_url, ',', b.help_topic_id + 1   ), ',', - 1 ) AS pictyres_url, s.opertime, s.source, s.teacher_id, s.publisher, c.top " +
                "        FROM    class_pictures c, pictures s   JOIN mysql.help_topic b    ON b.help_topic_id < (LENGTH(s.pictyres_url) - LENGTH(REPLACE (s.pictyres_url, ',', '')) + 1 " +
                "            )     WHERE c.class_id = ?        AND s.checks = 0  AND s.display = 1         AND c.pictures_id = s.id      AND c.school_id = s.school_id  " +
                "        ORDER BY c.top DESC, s.opertime DESC   LIMIT 0, 21  ";
        List<Map<String, Object>> mapList = banCardJdbc.queryListMap(sql, classid);

        //更新班级图片心跳
        // classCardFieldService.pushClassCard(Integer.parseInt(id.toString()), "picturesflag", flag);
        sql = " UPDATE bancard SET picturesflag=0 WHERE deviceid=?";
        banCardJdbc.updateByParameter(sql, deviceid);
        return mapList;
    }

    /**
     * @描述 查看班级视频
     * @创建人 zm
     * @创建时间 2020/2/15
     */
    @Override
    public List<Map<String, Object>> queryClassVideos(String deviceid) {
        Map<String, Object> stringObjectMap = banCardJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return null;
        }
        Object classid = stringObjectMap.get("classid");
        Object id = stringObjectMap.get("id");
        String sql = "SELECT s.id,s.video_name,s.video_url,s.opertime,s.source,s.teacher_id,s.publisher,c.top,'' video_cover FROM class_video c ,video s WHERE c.class_id=? AND s.checks=0 AND s.display=1 AND c.video_id=s.id AND c.school_id=s.school_id " +
                " ORDER BY c.top DESC,s.opertime DESC LIMIT 0,8";
        List<Map<String, Object>> mapList = null;
        try {
            mapList = banCardJdbc.queryListMap(sql, classid);
        } catch (Exception e) {
            logger.info("queryClassVideos-->error={}", e);
        }
        //更新班级视频心跳
        //classCardFieldService.pushClassCard(Integer.parseInt(id.toString()), "videoflag", flag);
        sql = " UPDATE bancard SET videoflag=0 WHERE deviceid=?";
        banCardJdbc.updateByParameter(sql, deviceid);
        return mapList;
    }

    /**
     * @描述 查看班级通知
     * @创建人 zm
     * @创建时间 2020/2/15
     */
    @Override
    public List<Map<String, Object>> queryClassNotices(String deviceid) {
        Map<String, Object> stringObjectMap = banCardJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return null;
        }
        Object classid = stringObjectMap.get("classid");
        Object school_id = stringObjectMap.get("school_id");
        String sql = "SELECT id,type,state,icon,publisher_id,publisher,content,opertime,title,body,student_id FROM  " +
                "   (SELECT n.id,0 type,n.state,'https://oss.yuguozhijia.online/icon/%E9%80%9A%E7%9F%A5x.png' icon,teacher_id publisher_id,publisher,n.content,DATE_FORMAT(n.opertime ,'%Y-%m-%d %H:%i') opertime,'通知管理' title , CONCAT(publisher,'教师: ',content) body " +
                "   ,0 student_id FROM notice  n,class_notice  c  WHERE c.class_id=? AND n.school_id=? AND n.display=1 AND c.notice_id=n.id  " +
                "  UNION  " +
                "SELECT c.id,c.type,c.state,a.icon,t.id publisher_id,t.student_name publisher,c.content,c.opertime,a.name title,CONCAT(t.student_name,'同学',c.content) body,c.student_id FROM all_notice c LEFT JOIN  application  a ON(c.jurisdiction_id=a.id) LEFT JOIN student t ON(t.id=c.student_id)  WHERE c.bancard=1 AND c.type=5  AND c.class_id=?  " +
                "  UNION  " +
                " SELECT c.id,c.type,c.state,j.image icon,t.id publisher_id,t.name publisher,c.content,c.opertime,j.name title,CONCAT(t.name,'教师',c.content) body,c.student_id FROM all_notice c LEFT JOIN  jurisdiction  j ON(c.jurisdiction_id=j.id) LEFT JOIN teacher  t ON(t.id=c.teacher_id)  WHERE c.bancard=1 AND c.type=1 AND c.class_id=?    " +
                "    UNION  " +
                " SELECT c.id,c.type,c.state,j.image icon,t.id publisher_id,t.name publisher,c.content,c.opertime,j.name title,CONCAT(t.name,'教师',c.content) body,c.student_id FROM all_notice c LEFT JOIN  jurisdiction  j ON(c.jurisdiction_id=j.id) LEFT JOIN teacher  t ON(t.id=c.teacher_id)  WHERE c.bancard=1 AND c.type=2 AND c.class_id=?   " +
                "    UNION  " +
                "  SELECT c.id,c.type,0 state,p.icon,t.id publisher_id,t.student_name publisher ,c.content ,c.opertime,p.name title, CONCAT(p.name,'：',t.student_name,'同学',c.content) body,c.student_id FROM all_notice c  " +
                " LEFT JOIN  application  p  ON(c.jurisdiction_id=p.id)   LEFT JOIN student  t ON(t.id=c.student_id) LEFT JOIN classes  s ON(s.id=c.class_id)   WHERE c.state IN (2,3,5,6) AND c.papplet=1 AND c.type=4 AND t.class_id=?   " +
                "    UNION  " +
                " SELECT c.id,c.type,c.state,j.image icon,t.id publisher_id,t.name publisher,c.content,c.opertime,j.name title,CONCAT(t.name,'教师发布了',c.content) body,c.student_id FROM all_notice c LEFT JOIN  jurisdiction  j ON(c.jurisdiction_id=j.id) LEFT JOIN teacher  t ON(t.id=c.teacher_id)  WHERE c.bancard=1 AND c.type=7 AND c.class_id=?   " +
                "   ) t ORDER BY opertime DESC LIMIT 0,10";
        //更新通知心跳
        //classCardFieldService.deviceidAndCards(deviceid, "noticeflag", flag + "");
        String sql2 = " UPDATE bancard SET noticeflag=0 WHERE deviceid=?";
        banCardJdbc.updateByParameter(sql2, deviceid);
        return banCardJdbc.queryListMap(sql, classid, school_id, classid, classid, classid, classid, classid);
    }

    /**
     * @描述 修改心跳接口状态
     * @创建人 zm
     * @创建时间 2020/2/15
     */
    @Override
    public int updateHeartbeat(String deviceid, String type) {
        String sql = " UPDATE bancard SET " + type + "=0 WHERE deviceid =?";
        return banCardJdbc.updateByParameter(sql, deviceid);
    }

    /**
     * @描述 绑定个推
     * @创建人 zm
     * @创建时间 2020/2/23
     */
    @Override
    public int updatePush(String deviceid, String clientid) {
        String sql = "UPDATE bancard SET clientid=?,devicetypeflag=1,bindflag=1, classflag=1, dutyflag=1, picturesflag=1, videoflag=1, noticeflag=1, timetableflag=1 WHERE deviceid=?";
        return banCardJdbc.updateByParameter(sql, clientid, deviceid);
    }

    /**
     * @描述 查询每周课表
     * @创建人 zm
     * @创建时间 2020/2/23
     */
    @Override
    public List<Map<String, Object>> queryTimetable(String deviceid) {
        List<Map<String, Object>> objects = null;
        try {
            Map<String, Object> stringObjectMap = banCardJdbc.queryDevice(deviceid);
            if (stringObjectMap == null) {
                return null;
            }
            Object classid = stringObjectMap.get("classid");
            Object school_id = stringObjectMap.get("school_id");
            String sql = "SELECT day week FROM class_day WHERE school_id=? ";
            Map<String, Object> map1 = banCardJdbc.queryMap(sql, school_id);
            if (map1 == null) {
                return null;
            }
            objects = new ArrayList<>();
            for (int i = 1; i <= (int) map1.get("week"); i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("week", i);
                String sql1 = "SELECT s.id,s.course_name,s.teacher_name,s.y+1 section, " +
                        "CONCAT(start_time,'-',end_time) time  FROM timetable s , attend_class_time " +
                        " t WHERE s.y=t.current_section AND t.school_id =? AND class_id=? AND s.x+1=? " +
                        " ORDER BY s.x,section ";
                List<Map<String, Object>> mapList = banCardJdbc.queryListMap(sql1, school_id, classid, i);
                map.put("list", mapList);
                objects.add(map);
            }
            Object id = stringObjectMap.get("id");
            //classCardFieldService.pushClassCard(Integer.parseInt(id.toString()), "timetableflag", flag);
            sql = " UPDATE bancard SET timetableflag=0 WHERE deviceid=?";
            banCardJdbc.updateByParameter(sql, deviceid);
        } catch (Exception e) {

        }
        return objects;
    }

    /**
     * @描述 查所有应用模块
     * @创建人 zm
     * @创建时间 2020/3/16
     */
    @Override
    public List<Map<String, Object>> queryApplicationAll(String deviceid) {
        Map<String, Object> stringObjectMap = banCardJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return null;
        }
        String sql = "SELECT j.id,j.image icon,j.name,j.url,j.type,j.sign FROM school_jurisdiction s,jurisdiction j WHERE s.jurisdiction_id=j.id AND s.bancard=1 AND s.school_id=? AND s.type=0  ORDER BY s.id";
        List<Map<String, Object>> maps = banCardJdbc.queryListMap(sql, stringObjectMap.get("school_id"));
        return maps;
    }

    /**
     * @描述 查询班级值日
     * @创建人 zm
     * @创建时间 2020/3/15
     */
    @Override
    public List<Map<String, Object>> queryTodayDuty(String deviceid) {
        Map<String, Object> stringObjectMap = banCardJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return null;
        }
        Object school_id = stringObjectMap.get("school_id");
        Object classid = stringObjectMap.get("classid");
        String sql = "SELECT id,projects,groups,school_id,class_id,DATE(starttime) starttime,type,`index`  FROM class_duty_time WHERE school_id=? AND class_id=? LIMIT 1";
        Map<String, Object> maps = null;
        try {
            maps = banCardJdbc.queryMap(sql, school_id, classid);
        } catch (Exception e) {
            logger.info("queryClassDutyAll==>maps,error={}", e);
        }
        if (maps == null) {
            return null;
        }
        sql = "SELECT day ints FROM class_day WHERE school_id=? ";
        Integer integer = banCardJdbc.queryInteger(sql, school_id);
        String groups = (String) maps.get("groups");
        String[] split = groups.split(",");
        Date time = (Date) maps.get("starttime");
        String starttime = DateUtil.parseData(time, "yyyy-MM-dd");
        Integer index = (Integer) maps.get("index");
        Integer type = (Integer) maps.get("type");
        String gettime = DateUtil.gettime();
        if (DateUtil.getDay(DateUtil.gettime(), starttime) > 0) {
            return null;
        }
        int length = split.length;
        long day = -1;
        if (type == 0) {//按天循环
            if (integer == 0) {//没有课表按天循环
                if (getDay(gettime)) {//今天是周末
                    return null;
                } else {//周六 周日
                    day = getDay(starttime, gettime);
                }
            } else {
                List<Integer> integers = new ArrayList<>();
                for (int i = 1; i <= integer; i++) {//根据课表循环值日组
                    if (integer != 7) {
                        integers.add(i);
                    } else {//为周日时0
                        integers.add(0);
                    }
                }
                if (!integers.contains(getDayInt(gettime))) {
                    return null;
                }
                day = getDay(starttime, gettime, integers);
            }
        }
        if (type == 1) {//按周循环
            day = DateUtil.calcWeekOffset(starttime, gettime);
        }

        long y = (day + index) % length;
        System.out.println(y);
        String sql1 = "SELECT s.student_name name,s.id,SUBSTRING_INDEX(SUBSTRING_INDEX(t.projects,',',c.x+1),',',-1) project,s.head_portrait FROM " +
                " class_duty c,class_duty_time t,student s   WHERE  c.class_id=t.class_id AND s.id=c.student_id AND " +
                " c.school_id=? AND c.class_id=? AND c.y=?";
        Object id = stringObjectMap.get("id");
        //classCardFieldService.pushClassCard(Integer.parseInt(id.toString()), "dutyflag", flag);
        sql = " UPDATE bancard SET dutyflag=0 WHERE deviceid=?";
        banCardJdbc.updateByParameter(sql, deviceid);
        return banCardJdbc.queryListMap(sql1, school_id, classid, y);
    }

    private long getDay(String startTime, String endTime, List<Integer> integers) {
        long a = -1;
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);
            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                int i = tempStart.get(Calendar.DAY_OF_WEEK) - 1;
                if (integers.contains(i)) {
                    a++;
                }
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return a;
    }


    private long getDay(String startTime, String endTime) {
        long a = -1;
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Date end = dateFormat.parse(endTime);
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);
            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
            while (tempStart.before(tempEnd)) {
                int i = tempStart.get(Calendar.DAY_OF_WEEK) - 1;
                if (i != 0 && i != 6) {
                    a++;
                }
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return a;
    }

    private static Boolean getDay(String startTime) {
        long a = 0;
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);
            int i = tempStart.get(Calendar.DAY_OF_WEEK) - 1;
            if (i != 0 && i != 6) {
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return true;
    }

    private int getDayInt(String startTime) {
        int i = -1;
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date start = dateFormat.parse(startTime);
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);
            i = tempStart.get(Calendar.DAY_OF_WEEK) - 1;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return i;
    }

    /**
     * @描述 查询所有值日信息
     * @创建人 zm
     * @创建时间 2020/4/22
     */
    @Override
    public Result queryDutyAll(String deviceid) {
        Map<String, Object> stringObjectMap = banCardJdbc.queryDevice(deviceid);
        if (stringObjectMap == null) {
            return new Result(CodeUtil.DEVICE_AFTER_OPERATION);
        }
        Object school_id = stringObjectMap.get("school_id");
        Object classid = stringObjectMap.get("classid");
        String sql = "SELECT id,projects,groups,school_id,class_id,DATE(starttime) starttime,type,`index`  FROM class_duty_time WHERE school_id=? AND class_id=? LIMIT 1";
        Map<String, Object> maps = null;
        try {
            maps = banCardJdbc.queryMap(sql, school_id, classid);
        } catch (Exception e) {
            logger.info("queryClassDutyAll==>maps,error={}", e);
        }
        if (maps == null) {
            return new Result();
        }
        sql = "SELECT day ints FROM class_day WHERE school_id=? ";
        Integer integer = banCardJdbc.queryInteger(sql, school_id);
        String groups = (String) maps.get("groups");
        String[] split = groups.split(",");
        Date time = (Date) maps.get("starttime");
        String starttime = DateUtil.parseData(time, "yyyy-MM-dd");
        Integer index = (Integer) maps.get("index");
        Integer type = (Integer) maps.get("type");
        String gettime = DateUtil.gettime();
        int length = split.length;
        long day = -1;
        if (type == 0) {//按天循环
            if (integer == 0) {//没有课表按天循环
                if (!getDay(gettime)) {//今天不是周末
                    day = getDay(starttime, gettime);
                }
            } else {
                List<Integer> integers = new ArrayList<>();
                for (int i = 1; i <= integer; i++) {//根据课表循环值日组
                    if (integer != 7) {
                        integers.add(i);
                    } else {//为周日时0
                        integers.add(0);
                    }
                }
                if (integers.contains(getDayInt(gettime))) {
                    day = getDay(starttime, gettime, integers);
                }
            }
        }
        if (type == 1) {//按周循环
            day = DateUtil.calcWeekOffset(starttime, gettime);
        }
        long y = (day + index) % length;
        logger.info("queryDutyAll,starttime={},day={},y={}", starttime, day, y);
        sql = "SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(t.groups,',',c.y+1),',',-1) 'group',c.y groupid,if(c.y=" + y + ",1,0) state ,t.type FROM  class_duty c,class_duty_time t   WHERE  c.class_id=t.class_id  AND  c.school_id=? AND c.class_id=?  GROUP BY c.y";
        if (DateUtil.getDay(DateUtil.gettime(), starttime) > 0) {
            sql = "SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(t.groups,',',c.y+1),',',-1) 'group',c.y groupid, 0 state ,t.type FROM  class_duty c,class_duty_time t   WHERE  c.class_id=t.class_id  AND  c.school_id=? AND c.class_id=?  GROUP BY c.y";
        }
        List<Map<String, Object>> maps1 = banCardJdbc.queryListMap(sql, school_id, classid);
        String sql1 = "SELECT s.student_name name,s.id,SUBSTRING_INDEX(SUBSTRING_INDEX(t.projects,',',c.x+1),',',-1) project,s.head_portrait FROM " +
                " class_duty c,class_duty_time t,student s   WHERE  c.class_id=t.class_id AND s.id=c.student_id AND " +
                " c.school_id=? AND c.class_id=? AND c.y=? ";
        for (int i = 0; i < maps1.size(); i++) {
            Map<String, Object> map = maps1.get(i);
            List<Map<String, Object>> maps2 = banCardJdbc.queryListMap(sql1, school_id, classid, map.get("groupid"));
            map.put("list", maps2);
        }
        return new Result(maps1);
    }
}
